package com.duapk.search.bean;

import java.util.HashSet;
import java.util.Set;

/**
 * 高亮信息
 * 
 * @Package: com.duapk.search.bean
 * @ClassName: HighlightInfo
 * @author: jiangzheng
 * @date: Apr 5, 2011 6:54:51 PM
 * 
 */
public class Highlighter {

	/**
	 * 需要高亮的词
	 */
	private Set<String> tokens;

	/**
	 * 高亮词的最小长度
	 */
	private int minWordLength;

	/**
	 * 高亮词的最大长度
	 */
	private int maxWordLength;

	public Highlighter(Set<String> tokens) {
		this.tokens = tokens;
		int minWordLength = Integer.MAX_VALUE;
		int maxWordLength = 1;
		for (String token : tokens) {
			int length = token.length();
			if (minWordLength > length) {
				minWordLength = length;
			}
			if (maxWordLength < length) {
				maxWordLength = length;
			}
		}
		this.minWordLength = minWordLength;
		this.maxWordLength = maxWordLength;
	}

	/**
	 * 对指定的文本进行高亮处理
	 * 
	 * @Title: highlight
	 * @author: jiangzheng
	 * @date: Apr 5, 2011 6:58:02 PM
	 * @param text
	 * @return
	 */
	public String highlight(String text) {
		StringBuilder result = new StringBuilder();
		int length = text.length();
		for (int i = 0; i < length;) {
			boolean matched = false;
			for (int j = i + maxWordLength; j >= i + minWordLength; j--) {
				if (j > length) {
					continue;
				}
				String substring = text.substring(i, j);
				if (tokens.contains(substring.toLowerCase())) {
					result.append("<em>").append(substring).append("</em>");
					matched = true;
					i = j;
					break;
				}
			}
			if (!matched) {
				result.append(text.charAt(i));
				i++;
			}
		}
		return result.toString();
	}
	
	public static void main(String[] args) {
		
		Set<String> tokens = new HashSet<String>();
		tokens.add("手机");
		tokens.add("qq");
		tokens.add("浏览器");
		Highlighter highlighter = new Highlighter(tokens);
		String title = "QQ";
		System.out.println(highlighter.highlight(title));
	}
}
